package com.mars.validate;


import com.mars.po.User;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.regex.Pattern;

@Component
public class UserValidator implements Validator {


    @Override
    public boolean supports(Class<?> aClass) {
        return User.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        User user = (User) o;
        ValidationUtils.rejectIfEmpty(errors, "email", "user.email.require");
        ValidationUtils.rejectIfEmpty(errors, "phone", "user.phone.require");
        ValidationUtils.rejectIfEmpty(errors, "password", "user.password.require");
        ValidationUtils.rejectIfEmpty(errors,"username","user.username.require");
        if (!Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$").matcher(user.getPhone()).matches()) {
            errors.rejectValue("phone", "phone.invalid");
        }
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        if (!Pattern.compile(check).matcher(user.getEmail()).matches()) {
            errors.rejectValue("email", "email.invalid");
        }
    }
}
